package com.qeeyou.apps.android.craftsman.activity.publish;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.adapter.InstallTypeGridAdapter;
import com.qeeyou.apps.android.craftsman.common.Contants;
import com.qeeyou.apps.android.craftsman.po.AreaInfo;
import com.qeeyou.apps.android.craftsman.po.InstallTypeInfo;
import com.qeeyou.apps.android.craftsman.po.InstallShopInfo;
import com.qeeyou.apps.android.craftsman.po.UserAddressInfo;
import com.qeeyou.apps.android.craftsman.service.AppService;
import com.qeeyou.apps.android.craftsman.service.UserService;
import com.qeeyou.apps.android.craftsman.view.BottomDialog;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;
import com.qeeyou.apps.android.craftsman.view.PublishSelectButton;
import com.qeeyou.apps.android.craftsman.view.wheelview.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PublishActivity extends Activity {

    private ImageView btnBack;
    private LinearLayout btnAddress;
    private PublishSelectButton btnInstallTime;
    private PublishSelectButton btnWorkingDay;
    private PublishSelectButton btnInstallNum;

    private LinearLayout btnPublish;


    private BottomDialog bottomDialog;

    private TextView tvAddressName;                           //地址用户名
    private TextView tvAddressPhone;                          //地址手机号
    private TextView tvAddress;                               //地址

    private CustomLoadingDialog mLoadingDialog;
    private List<AreaInfo> mAreaList = new ArrayList<AreaInfo>();

    private RecyclerView rvInstallType;
    private InstallTypeGridAdapter mInstallTypeAdapter;
    private List<InstallTypeInfo> mInstallTypeList = new ArrayList<>();

    private InstallTypeInfo mInstallTypeInfo;
    private UserAddressInfo mUserAddressInfo;
    private InstallShopInfo mInstallShopInfo;
    private String mInstallTime;
    private String mWorkingDay;
    private String mInstallNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);

        Intent intent = getIntent();
        if(intent != null && intent.getSerializableExtra("shopInfo") != null) {
            mInstallShopInfo = (InstallShopInfo) intent.getSerializableExtra("shopInfo");
        }

        setView();
        setEvent();

        loadData();

    }

    private void setView() {
        btnBack = (ImageView) this.findViewById(R.id.btnBack4Publish);
        btnAddress = (LinearLayout) this.findViewById(R.id.btnAddress4Publish);
        btnInstallTime = (PublishSelectButton) this.findViewById(R.id.btnInstallTime4Publish);
        btnWorkingDay = (PublishSelectButton) this.findViewById(R.id.btnWorkingDay4Publish);
        btnInstallNum = (PublishSelectButton) this.findViewById(R.id.btnInstallNum4Publish);
        btnPublish = (LinearLayout) this.findViewById(R.id.btnPublish4Publish);

        tvAddressName = (TextView) this.findViewById(R.id.tvAddressName4Publish);
        tvAddressPhone = (TextView) this.findViewById(R.id.tvAddressPhone4Publish);
        tvAddress = (TextView) this.findViewById(R.id.tvAddress4Publish);

        rvInstallType = (RecyclerView) this.findViewById(R.id.rvInstallType4Publish);
    }

    private void setEvent() {
        btnBack.setOnClickListener(onBackClickListener);
        btnAddress.setOnClickListener(onAddressClickListener);
        btnInstallTime.setOnClickListener(onInstallTimeClickListener);
        btnWorkingDay.setOnClickListener(onWorkingDayClickListener);
        btnInstallNum.setOnClickListener(onInstallNumClickListener);
        btnPublish.setOnClickListener(onPublishClickListener);

        GridLayoutManager manager = new GridLayoutManager(this, 4);
        rvInstallType.setLayoutManager(manager);
        mInstallTypeAdapter = new InstallTypeGridAdapter(this,
                mInstallTypeList);
        rvInstallType.setAdapter(mInstallTypeAdapter);
        mInstallTypeAdapter.setOnItemClickListener(new InstallTypeGridAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mInstallTypeAdapter.setSelectPosition(position);
                //选中的安装类型
                mInstallTypeInfo = mInstallTypeList.get(position);
            }
        });
    }

    private void loadData() {
        new GetUserAddressList().execute();
        String[] params = {"1"};
        new GetInstallTypeList().execute(params);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Contants.RequestCode.REQUEST_CODE_WORKING_DAY) {
            if (resultCode == RESULT_OK) {
                String workingDay = data.getStringExtra("working_day");
                btnWorkingDay.setText(workingDay);
                mWorkingDay = workingDay;
            } else {
                btnWorkingDay.setText(null);
                mWorkingDay = null;
            }
        } else if (requestCode == Contants.RequestCode.REQUEST_SELECT_ADDRESS) {
            if (resultCode == RESULT_OK) {
                mUserAddressInfo = data.getParcelableExtra(Contants.Extra.EXTRA_ADDRESS_INFO);
                refreshAddressInfo(mUserAddressInfo);
            }
        } else {
            mUserAddressInfo = null;
        }
    }

    //返回按钮
    private View.OnClickListener onBackClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PublishActivity.this.finish();
        }
    };

    //地址按钮
    private View.OnClickListener onAddressClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(PublishActivity.this, AddressActivity.class);
            PublishActivity.this.startActivityForResult(intent, Contants.RequestCode.REQUEST_SELECT_ADDRESS);
        }
    };

    //上门安装时间
    private View.OnClickListener onInstallTimeClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TimePickerView pickerView = new TimePickerView.Builder(PublishActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date);
                    btnInstallTime.setText(dateStr);
                    mInstallTime = dateStr;
                }
            }).setType(new boolean[]{true, true, true, true, true, false})
                    .setRange(Calendar.getInstance().get(Calendar.YEAR) - 5, Calendar.getInstance().get(Calendar.YEAR) + 5).build();
            pickerView.setDate(Calendar.getInstance());
            pickerView.show();
        }
    };

    //安装工期
    private View.OnClickListener onWorkingDayClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(PublishActivity.this, WorkingDayActivity.class);
            PublishActivity.this.startActivityForResult(intent, Contants.RequestCode.REQUEST_CODE_WORKING_DAY);
        }
    };

    //安装数量
    private View.OnClickListener onInstallNumClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO -- 弹出选择框
            View view = LayoutInflater.from(PublishActivity.this).inflate(R.layout.dialog_intall_amount, null);
            WheelView wheelView1 = view.findViewById(R.id.wheelView4InstallAmount);
            Button btnConfirm = (Button) view.findViewById(R.id.btnConfirm4InstallAmount);
            Button btnCancel = (Button) view.findViewById(R.id.btnCancel4InstallAmount);
            wheelView1.setItems(getNumbers(), 0);//init selected position is 0 初始选中位置为0
            mInstallNum = "1";
            wheelView1.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(int selectedIndex, String item) {
                    mInstallNum = item;
                }
            });
            btnConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnInstallNum.setText(mInstallNum);
                    bottomDialog.dismiss();
                }
            });
            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bottomDialog.dismiss();
                }
            });
            //防止弹出两个窗口
            if (bottomDialog != null && bottomDialog.isShowing()) {
                return;
            }
            bottomDialog = new BottomDialog(PublishActivity.this, R.style.ActionSheetDialogStyle);
            //将布局设置给Dialog
            bottomDialog.setContentView(view);
            bottomDialog.show();//显示对话框
        }
    };

    private ArrayList getNumbers() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 1; i < 100; i++) {
            list.add(i + "");
        }
        return list;
    }

    //发布按钮
    private View.OnClickListener onPublishClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mInstallShopInfo == null) {
                Toast.makeText(PublishActivity.this, "未添加安装商品", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mUserAddressInfo == null) {
                Toast.makeText(PublishActivity.this, "请添加用户地址", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mInstallTime == null || mInstallTime.trim().equalsIgnoreCase("")) {
                Toast.makeText(PublishActivity.this, "请添加安装时间", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mWorkingDay == null || mWorkingDay.trim().equalsIgnoreCase("")) {
                Toast.makeText(PublishActivity.this, "请添加安装工期", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mInstallNum == null || mInstallNum.trim().equalsIgnoreCase("")) {
                Toast.makeText(PublishActivity.this, "请添加安装数量", Toast.LENGTH_SHORT).show();
                return;
            }
            if(mInstallTypeInfo == null) {
                Toast.makeText(PublishActivity.this, "请选择安装类型", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(PublishActivity.this, PublishStep2Activity.class);
            intent.putExtra(Contants.Extra.EXTRA_ADDRESS_INFO, mUserAddressInfo);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_TIME, mInstallTime);
            intent.putExtra(Contants.Extra.EXTRA_WORKING_DAY, mWorkingDay);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_NUM, mInstallNum);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_TYPE, mInstallTypeInfo);
            intent.putExtra(Contants.Extra.EXTRA_INSTALL_SHOP, mInstallShopInfo);
            startActivity(intent);
        }
    };


    class GetUserAddressList extends AsyncTask<String, Void, List<UserAddressInfo>> {

        public GetUserAddressList() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(PublishActivity.this);
            }
            mLoadingDialog.setMessage("正在获取用户地址列表...");
            mLoadingDialog.show();
        }

        @Override
        protected List<UserAddressInfo> doInBackground(String... params) {
            Map<String, String> paramMap = new HashMap<String, String>();
            List<UserAddressInfo> masterList = UserService.getInstance().getUserAddressList(paramMap);
            return masterList;
        }

        @Override
        protected void onPostExecute(List<UserAddressInfo> addressList) {
            super.onPostExecute(addressList);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (addressList != null && addressList.size() > 0) {
                for (UserAddressInfo addressInfo : addressList) {
                    if (addressInfo.getIsdefault().equals("1")) {
                        mUserAddressInfo = addressInfo;
                        break;
                    }
                }
            }

            if (mUserAddressInfo != null) {
                refreshAddressInfo(mUserAddressInfo);
            }
        }
    }

    private void refreshAddressInfo(UserAddressInfo addressInfo) {
        tvAddressName.setText(addressInfo.getName());
        tvAddressPhone.setText(addressInfo.getContactway());
        String province = "";
        String city = "";
        if (!TextUtils.isEmpty(addressInfo.getProvinceid())
                && !TextUtils.isEmpty(addressInfo.getCityid())) {
            for (AreaInfo provinceInfo : mAreaList) {
                if (provinceInfo.getId().equals(addressInfo.getProvinceid())) {
                    province = provinceInfo.getName();
                    for (AreaInfo cityInfo : provinceInfo.getNexts()) {
                        if (cityInfo.getId().equals(addressInfo.getCityid())) {
                            city = cityInfo.getName();
                        }
                    }
                }
            }
        }
        tvAddress.setText(province + city + addressInfo.getAddress());
    }

    //获取安装类型
    class GetInstallTypeList extends AsyncTask<String, Void, List<InstallTypeInfo>> {
        public GetInstallTypeList() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(PublishActivity.this);
            }
            mLoadingDialog.setMessage("正在获取安装类型...");
            mLoadingDialog.show();
        }

        @Override
        protected void onPostExecute(List<InstallTypeInfo> typeList) {
            super.onPostExecute(typeList);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (typeList != null) {
                mInstallTypeList.clear();
                mInstallTypeList.addAll(typeList);
                mInstallTypeAdapter.setItems(mInstallTypeList);
            }
        }

        @Override
        protected List<InstallTypeInfo> doInBackground(String... params) {
            String releaseType = params[0];
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("releasetype", releaseType);
            List<InstallTypeInfo> typeList = AppService.getInstance().getInstallTypeList(paramMap);
            return typeList;
        }
    }

}
